package com.example.mydy;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.api.ApiClient;
import com.example.mydy.api.UserApi;
import com.example.mydy.model.Advertisement;
import com.example.mydy.model.AdvertisementListResponse;
import com.example.mydy.model.CommonResponse;
import com.example.mydy.utils.NetworkUtils;
import com.example.mydy.utils.MockDataManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class AdvertisementManagementActivity extends AppCompatActivity {
    private static final String TAG = "AdvertisementActivity";
    private static final int REQUEST_IMAGE_PICK = 100;
    private static final int REQUEST_STORAGE_PERMISSION = 101;
    
    private RecyclerView rvAdvertisements;
    private SwipeRefreshLayout swipeRefreshLayout;
    private FloatingActionButton fabAddAd;
    private ProgressBar progressBar;
    private TextView tvNoAds;
    private androidx.appcompat.widget.Toolbar toolbar;
    
    private List<Advertisement> advertisements = new ArrayList<>();
    private AdvertisementAdapter adapter;
    private UserApi userApi;
    
    // 用于存储当前选中的图片Uri
    private Uri selectedImageUri;
    private AlertDialog currentDialog;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advertisement_management);
        
        initViews();
        initApi();
        setupRecyclerView();
        loadAdvertisements();
        
        fabAddAd.setOnClickListener(v -> showAddAdvertisementDialog());
    }
    
    private void initViews() {
        // 初始化视图组件
        toolbar = findViewById(R.id.toolbar_ad_management);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        
        // 设置返回按钮
        findViewById(R.id.btn_back).setOnClickListener(v -> {
            finish(); // 返回上一页
        });
        
        // 设置刷新按钮
        findViewById(R.id.btn_refresh).setOnClickListener(v -> {
            refreshAdvertisements(); // 刷新广告列表
        });
        
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        rvAdvertisements = findViewById(R.id.rv_advertisements);
        progressBar = findViewById(R.id.progress_bar);
        tvNoAds = findViewById(R.id.tv_no_advertisements);
        fabAddAd = findViewById(R.id.fab_add_advertisement);

        // 配置下拉刷新
        swipeRefreshLayout.setOnRefreshListener(this::loadAdvertisements);
    }
    
    private void initApi() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiClient.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        userApi = retrofit.create(UserApi.class);
    }
    
    private void setupRecyclerView() {
        adapter = new AdvertisementAdapter(this, advertisements);
        adapter.setOnItemClickListener(new AdvertisementAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                // 处理广告项点击事件
                Toast.makeText(AdvertisementManagementActivity.this, "点击了广告: " + advertisements.get(position).getTitle(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEditClick(int position) {
                // 处理编辑按钮点击
                Advertisement ad = advertisements.get(position);
                Toast.makeText(AdvertisementManagementActivity.this, "编辑广告: " + ad.getTitle(), Toast.LENGTH_SHORT).show();
                showEditAdvertisementDialog(ad, position);
            }

            @Override
            public void onDeleteClick(int position) {
                // 处理删除按钮点击
                Advertisement ad = advertisements.get(position);
                Toast.makeText(AdvertisementManagementActivity.this, "删除广告: " + ad.getTitle(), Toast.LENGTH_SHORT).show();
                new AlertDialog.Builder(AdvertisementManagementActivity.this)
                    .setTitle("确认删除")
                    .setMessage("确定要删除这条广告吗？")
                    .setPositiveButton("确定", (dialog, which) -> deleteAdvertisement(advertisements.get(position), position))
                    .setNegativeButton("取消", null)
                    .show();
            }
        });
        rvAdvertisements.setLayoutManager(new LinearLayoutManager(this));
        rvAdvertisements.setAdapter(adapter);
    }
    
    private void loadAdvertisements() {
        progressBar.setVisibility(View.VISIBLE);
        tvNoAds.setVisibility(View.GONE);
        
        // 离线模式
        if (NetworkUtils.USE_OFFLINE_MODE) {
            advertisements.clear();
            advertisements.addAll(MockDataManager.getInstance().getAdvertisements());
            adapter.updateData(advertisements);
            progressBar.setVisibility(View.GONE);
            swipeRefreshLayout.setRefreshing(false);
            
            // 更新空视图
            if (advertisements.isEmpty()) {
                tvNoAds.setVisibility(View.VISIBLE);
            }
            return;
        }
        
        // 在线模式
        String token = NetworkUtils.getAuthToken();
        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        userApi.getAdvertisements("Bearer " + token).enqueue(new Callback<AdvertisementListResponse>() {
            @Override
            public void onResponse(Call<AdvertisementListResponse> call, Response<AdvertisementListResponse> response) {
                progressBar.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);
                
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        advertisements.clear();
                        
                        if (response.body().getAdvertisements() != null) {
                            advertisements.addAll(response.body().getAdvertisements());
                        }
                        
                        adapter.updateData(advertisements);
                        
                        // 更新空视图
                        if (advertisements.isEmpty()) {
                            tvNoAds.setVisibility(View.VISIBLE);
                        }
                    } else {
                        Toast.makeText(AdvertisementManagementActivity.this, "获取广告列表失败: " + response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(AdvertisementManagementActivity.this, "获取广告列表失败，错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AdvertisementListResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(AdvertisementManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void showAddAdvertisementDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_add_advertisement, null);
        builder.setView(view);
        
        EditText etTitle = view.findViewById(R.id.et_ad_title);
        EditText etContent = view.findViewById(R.id.et_ad_content);
        EditText etLink = view.findViewById(R.id.et_ad_link);
        Button btnSelectImage = view.findViewById(R.id.btn_select_image);
        ImageView ivPreview = view.findViewById(R.id.iv_ad_image_preview);
        
        // 重置图片选择
        selectedImageUri = null;
        ivPreview.setVisibility(View.GONE);
        
        btnSelectImage.setOnClickListener(v -> {
            checkPermissionAndPickImage();
        });
        
        builder.setTitle("添加广告")
                .setPositiveButton("添加", null)
                .setNegativeButton("取消", null);
        
        currentDialog = builder.create();
        currentDialog.show();
        
        currentDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            String title = etTitle.getText().toString().trim();
            String content = etContent.getText().toString().trim();
            String link = etLink.getText().toString().trim();
            
            if (TextUtils.isEmpty(title) || TextUtils.isEmpty(content)) {
                Toast.makeText(AdvertisementManagementActivity.this, "标题和内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (selectedImageUri == null) {
                Toast.makeText(AdvertisementManagementActivity.this, "请选择一张图片", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 离线模式
            if (NetworkUtils.USE_OFFLINE_MODE) {
                // 创建新广告对象
                Advertisement ad = new Advertisement();
                ad.setId(advertisements.size() + 1);
                ad.setTitle(title);
                ad.setContent(content);
                ad.setLink(link);
                ad.setImageUrl(selectedImageUri.toString());
                ad.setCreatedAt(new Date());
                
                // 将广告保存到MockDataManager
                boolean success = MockDataManager.addAdvertisement(ad);
                
                if (success) {
                    // 重新加载数据以确保显示最新内容
                    loadAdvertisements();
                    Toast.makeText(AdvertisementManagementActivity.this, "广告添加成功（离线模式）", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(AdvertisementManagementActivity.this, "广告添加失败", Toast.LENGTH_SHORT).show();
                }
                currentDialog.dismiss();
                return;
            }
            
            // 在线模式
            uploadImageAndCreateAd(title, content, link);
        });
    }
    
    private void uploadImageAndCreateAd(String title, String content, String link) {
        progressBar.setVisibility(View.VISIBLE);
        
        // 此处为上传图片的实现，实际应用中需要根据自己的API进行调整
        File imageFile = new File(selectedImageUri.getPath());
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), imageFile);
        MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image", imageFile.getName(), requestFile);
        
        // 创建其他字段
        RequestBody titleBody = RequestBody.create(MediaType.parse("text/plain"), title);
        RequestBody contentBody = RequestBody.create(MediaType.parse("text/plain"), content);
        RequestBody linkBody = RequestBody.create(MediaType.parse("text/plain"), link);
        
        String token = NetworkUtils.getAuthToken();
        
        userApi.uploadAdImage("Bearer " + token, imagePart).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    // 获取上传后的图片URL
                    String imageUrl = "";
                    Object data = response.body().getData();
                    if (data instanceof Map) {
                        Map<String, Object> dataMap = (Map<String, Object>) data;
                        imageUrl = (String) dataMap.get("url");
                    }
                    
                    createAdvertisement(title, content, link, imageUrl);
                } else {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(AdvertisementManagementActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(AdvertisementManagementActivity.this, "图片上传失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void createAdvertisement(String title, String content, String link, String imageUrl) {
        Map<String, Object> adData = new HashMap<>();
        adData.put("title", title);
        adData.put("content", content);
        adData.put("link", link);
        adData.put("imageUrl", imageUrl);
        
        String token = NetworkUtils.getAuthToken();
        
        userApi.createAdvertisement("Bearer " + token, adData).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                progressBar.setVisibility(View.GONE);
                
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        Toast.makeText(AdvertisementManagementActivity.this, "广告添加成功", Toast.LENGTH_SHORT).show();
                        currentDialog.dismiss();
                        loadAdvertisements();
                    } else {
                        Toast.makeText(AdvertisementManagementActivity.this, "广告添加失败: " + response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(AdvertisementManagementActivity.this, "广告添加失败，错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(AdvertisementManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void checkPermissionAndPickImage() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
        } else {
            pickImageFromGallery();
        }
    }
    
    private void pickImageFromGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                pickImageFromGallery();
            } else {
                Toast.makeText(this, "需要存储权限以选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            selectedImageUri = data.getData();
            
            if (currentDialog != null && currentDialog.isShowing()) {
                ImageView ivPreview = currentDialog.findViewById(R.id.iv_ad_image_preview);
                
                if (ivPreview != null) {
                    ivPreview.setVisibility(View.VISIBLE);
                    Picasso.get().load(selectedImageUri).into(ivPreview);
                }
            }
        }
    }
    
    private void deleteAdvertisement(Advertisement ad, int position) {
        // 离线模式
        if (NetworkUtils.USE_OFFLINE_MODE) {
            boolean success = MockDataManager.deleteAdvertisement(ad.getId());
            if (success) {
                advertisements.remove(position);
                adapter.notifyItemRemoved(position);
                Toast.makeText(this, "广告删除成功（离线模式）", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "广告删除失败", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        
        // 在线模式
        progressBar.setVisibility(View.VISIBLE);
        String token = NetworkUtils.getAuthToken();
        
        userApi.deleteAdvertisement("Bearer " + token, ad.getId()).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                progressBar.setVisibility(View.GONE);
                
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        advertisements.remove(position);
                        adapter.notifyItemRemoved(position);
                        Toast.makeText(AdvertisementManagementActivity.this, "广告删除成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(AdvertisementManagementActivity.this, "广告删除失败: " + response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(AdvertisementManagementActivity.this, "广告删除失败，错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(AdvertisementManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void showEditAdvertisementDialog(Advertisement ad, int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_add_advertisement, null);
        builder.setView(view);
        
        EditText etTitle = view.findViewById(R.id.et_ad_title);
        EditText etContent = view.findViewById(R.id.et_ad_content);
        EditText etLink = view.findViewById(R.id.et_ad_link);
        Button btnSelectImage = view.findViewById(R.id.btn_select_image);
        ImageView ivPreview = view.findViewById(R.id.iv_ad_image_preview);
        
        // 设置原始数据
        etTitle.setText(ad.getTitle());
        etContent.setText(ad.getContent());
        etLink.setText(ad.getLink());
        
        // 设置图片
        if (ad.getImageUrl() != null && !ad.getImageUrl().isEmpty()) {
            selectedImageUri = Uri.parse(ad.getImageUrl());
            try {
                ivPreview.setVisibility(View.VISIBLE);
                Picasso.get().load(selectedImageUri).into(ivPreview);
            } catch (Exception e) {
                Log.e(TAG, "加载图片失败: " + e.getMessage());
                ivPreview.setVisibility(View.GONE);
            }
        }
        
        btnSelectImage.setOnClickListener(v -> {
            checkPermissionAndPickImage();
        });
        
        builder.setTitle("编辑广告")
                .setPositiveButton("保存", null)
                .setNegativeButton("取消", null);
        
        currentDialog = builder.create();
        currentDialog.show();
        
        currentDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            String title = etTitle.getText().toString().trim();
            String content = etContent.getText().toString().trim();
            String link = etLink.getText().toString().trim();
            
            if (TextUtils.isEmpty(title) || TextUtils.isEmpty(content)) {
                Toast.makeText(AdvertisementManagementActivity.this, "标题和内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 离线模式下直接更新广告
            if (NetworkUtils.USE_OFFLINE_MODE) {
                ad.setTitle(title);
                ad.setContent(content);
                ad.setLink(link);
                if (selectedImageUri != null) {
                    ad.setImageUrl(selectedImageUri.toString());
                }
                
                // 将更新后的广告保存到MockDataManager
                boolean success = MockDataManager.updateAdvertisement(ad);
                
                if (success) {
                    // 更新本地列表
                    advertisements.set(position, ad);
                    adapter.notifyItemChanged(position);
                    currentDialog.dismiss();
                    Toast.makeText(AdvertisementManagementActivity.this, "广告更新成功（离线模式）", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(AdvertisementManagementActivity.this, "广告更新失败", Toast.LENGTH_SHORT).show();
                }
                return;
            }
            
            // 在线模式上传图片和更新广告
            if (selectedImageUri != null && !selectedImageUri.toString().equals(ad.getImageUrl())) {
                uploadImageAndUpdateAd(title, content, link, ad, position);
            } else {
                // 图片没有变化，直接更新其他信息
                updateAdvertisement(title, content, link, ad.getImageUrl(), ad, position);
            }
        });
    }
    
    private void uploadImageAndUpdateAd(String title, String content, String link, Advertisement ad, int position) {
        progressBar.setVisibility(View.VISIBLE);
        
        // 处理图片上传
        File imageFile = new File(selectedImageUri.getPath());
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), imageFile);
        MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image", imageFile.getName(), requestFile);
        
        String token = NetworkUtils.getAuthToken();
        
        userApi.uploadAdImage("Bearer " + token, imagePart).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    // 获取上传后的图片URL
                    String imageUrl = "";
                    Object data = response.body().getData();
                    if (data instanceof Map) {
                        Map<String, Object> dataMap = (Map<String, Object>) data;
                        imageUrl = (String) dataMap.get("url");
                    }
                    
                    updateAdvertisement(title, content, link, imageUrl, ad, position);
                } else {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(AdvertisementManagementActivity.this, "图片上传失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(AdvertisementManagementActivity.this, "图片上传失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void updateAdvertisement(String title, String content, String link, String imageUrl, Advertisement ad, int position) {
        Map<String, Object> adData = new HashMap<>();
        adData.put("title", title);
        adData.put("content", content);
        adData.put("link", link);
        adData.put("imageUrl", imageUrl);
        
        String token = NetworkUtils.getAuthToken();
        
        userApi.updateAdvertisement("Bearer " + token, ad.getId(), adData).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                progressBar.setVisibility(View.GONE);
                
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        ad.setTitle(title);
                        ad.setContent(content);
                        ad.setLink(link);
                        ad.setImageUrl(imageUrl);
                        
                        adapter.notifyItemChanged(position);
                        currentDialog.dismiss();
                        Toast.makeText(AdvertisementManagementActivity.this, "广告更新成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(AdvertisementManagementActivity.this, "广告更新失败: " + response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(AdvertisementManagementActivity.this, "广告更新失败，错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(AdvertisementManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    private void refreshAdvertisements() {
        // 显示刷新动画
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(true);
        }
        
        // 重新加载广告列表
        loadAdvertisements();
    }
}